package com.guli.gulimall.product.service.impl;

import com.guli.gulimall.product.dao.AttrDao;
import com.guli.gulimall.product.entity.AttrEntity;
import com.guli.gulimall.product.vo.AttrGroupVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.common.utils.PageUtils;
import com.guli.common.utils.Query;

import com.guli.gulimall.product.dao.AttrGroupDao;
import com.guli.gulimall.product.entity.AttrGroupEntity;
import com.guli.gulimall.product.service.AttrGroupService;
import org.w3c.dom.Attr;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Autowired
    AttrDao attrDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catalogId) {
        QueryWrapper<AttrGroupEntity> w = new QueryWrapper<>();
        if (!catalogId.equals(0L)) {
            w.eq("catalog_id",catalogId);
        }
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            w.and(qw->
                    qw.like("attr_group_name",key).or().eq("attr_group_id",key)
            );
        }
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                w
        );

        return new PageUtils(page);
    }

    @Override
    public List<AttrGroupVo> withattr(Long catalogId) {
        QueryWrapper<AttrGroupEntity> w = new QueryWrapper<>();
        w.eq("catalog_id",catalogId);
        List<AttrGroupEntity> attrGroups = baseMapper.selectList(w);
        List<AttrGroupVo> attrGroupVoList = attrGroups.stream().map(g -> {
            AttrGroupVo attrGroupVo = new AttrGroupVo();
            BeanUtils.copyProperties(g, attrGroupVo);
            QueryWrapper<AttrEntity> w2 = new QueryWrapper<>();
            w2.eq("attr_group_id", g.getAttrGroupId());
            //规格参数
            w2.eq("attr_type", 1);
            List<AttrEntity> attrs = attrDao.selectList(w2);
            attrGroupVo.setAttrs(attrs);
            return attrGroupVo;
        }).collect(Collectors.toList());
        return attrGroupVoList;
    }

}
